//
//  ONNetworkManager.swift
//  OnceNectar
//
//  Created by Zhang Dream on 2018/6/19.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import Foundation
import Alamofire
import PKHUD

struct ONNetworkManager {
    static func requestFile(urlString:String,params:[String:Any], method:HTTPMethod,success:@escaping(_ response:[String:Any])->()){
        //这里是接口和参数
        let url = appendUrl(suffix: urlString)
        
        //
        Alamofire.upload(multipartFormData: { (formdata) in
            //这里因为不同接口的参数名肯定不一样，所以就用你传的参数名。
            for (key,value) in params{
                
                //然后formdata只接受Data所以这里转换一下
                if let content = value as? String {
                    formdata.append(content.data(using: String.Encoding.utf8)!, withName: key)
                }
                
                // 如果是图片的话吧图片转化成Data
                if let content = value as? UIImage{
//                    formdata.append(content.getData(), withName: key)
                    formdata.append(content.getData(), withName: "file", mimeType: "image/*")
                 //   appendBodyPart(data: content.getData(), name: "file", fileName: "fileasdsad", mimeType: "image/*")
                }
                
                
            }
        }, usingThreshold: (5*1024*1024), to: url, method: method, headers: ["token":MineInfoModel.share.token!, "fs": "1"]) { (result) in
            switch result {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    //自己封装的处理请求返回的结果
                    //                    self.responseApply(response, success: success)
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
 
    
}

public class AlamofireWrapper: NSObject{
    
    @objc public class func request(url: String, meth: String, parameters: [String: Any], callBack: @escaping (_ request: NSURLRequest?, _ response: HTTPURLResponse?, _ json: [NSObject: AnyObject]?) -> ()){
        var m : HTTPMethod?
        if meth == "get" {
            m = .get
        }else {
            m = .post
        }
        Alamofire.request(url, method: m!,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    callBack(nil, nil, result as [NSObject : AnyObject])
                                }
                            }
                            else{
                                CustomShowAlertView().show(title: "请求失败", showTime: 2) {
                                   
                                }
                            }
        }
    }
   @objc public class func hidePro() -> Void {
        HUD.hide { (hide) in
            
        }
    }
   @objc public class func showHudPro() -> Void {
        HUD.show(.progress)
    }
    
}

//图片转Data有可能会为空，解决办法是把要转换的图片重新绘制下就行了
extension UIImage{
    //MARK:-----------图片转data-------------//
    func getData() -> Data{
        let data = UIImageJPEGRepresentation(self.getNewImage(), 0.9)
        return data!
    }
    //MARK:-----------重新绘制一下图形-------------//
    fileprivate func getNewImage() -> UIImage{
        let w = self.size.width
        let h = self.size.height
       
        UIGraphicsBeginImageContext(self.size)
        self.draw(in: CGRect(x: 0, y: 0, width: w, height: h))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}

